package com.example.mydownloader.mymodule.http

import com.example.mydownloader.data.model.inputdata.ResponseTemplate
import com.example.mydownloader.mymodule.gson.GsonUtil
import com.google.gson.Gson
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.lang.StringBuilder
import java.util.concurrent.TimeUnit


/**
 * <Description> POST,GET请求封装
 *
 * @author Wallace
 * @Date 2021/11/24 14:48
 */
object HttpUtil {
    /**
     * 创建默认的OkHttpClient对象
     */
    val okHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .cookieJar(MyCookie)
            .addInterceptor(EncryptInterceptor)
            .addInterceptor(TimeStampInterceptor)
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(60L, TimeUnit.SECONDS)
            .writeTimeout(60L, TimeUnit.SECONDS)
            .build()
    }

    fun createGetRequest(
        url: String,
        data: HashMap<String, String>?,
        headers: HashMap<String, String>? = null
    ): Request {
        val sb = StringBuilder(url)
        if (data != null) {
            sb.append("?")
            data.forEach {
                sb.append(it.key).append("=").append(it.value).append("&")
            }
            sb.deleteCharAt(sb.length - 1)
        }
        val requestBuilder = Request.Builder()
        return requestBuilder.url(sb.toString()).addHeaders(headers).get().build()
    }

    fun get(
        url: String,
        data: HashMap<String, String>?,
        headers: HashMap<String, String>? = null
    ): String? {
        val request = createGetRequest(url, data, headers)
        return getMessageFromServer(request)
    }

    fun postJson(url: String, data: Any?, headers: HashMap<String, String>? = null): String? {
        val json = if (data == null) null else {
            GsonUtil.toJson(data)
        }
        return postJson(url, json, headers)
    }

    fun postJson(
        url: String,
        json: String?,
        headers: HashMap<String, String>? = null
    ): String? {
        var requestBody: RequestBody? = null
        val requestBuilder = Request.Builder()
        requestBuilder.url(url).addHeaders(headers)
        if (json != null) {
            requestBody = json.toRequestBody("application/json".toMediaType())
        }
        val request = requestBuilder.method("POST", requestBody).build()
        return getMessageFromServer(request)
    }

    /**
     * @Author Wallace
     * @Description 封装POST请求
     * @Date 2021/11/24 15:53
     * @param url 请求url
     * @param headers 请求头
     * @param params 放入body的参数
     * @return
     */
    fun postForm(
        url: String,
        headers: HashMap<String, String>?,
        params: HashMap<String, String>?,
    ): Request {
        val requestBuilder = Request.Builder()
        requestBuilder.url(url).addHeaders(headers).addFormBody(params)
        return requestBuilder.build()
    }

    private fun getMessageFromServer(request: Request): String? {
        val response = okHttpClient.newCall(request).execute()
        var responseTemplate: ResponseTemplate? = null
        if (response.isSuccessful) {
            val result = response.body?.string()
            responseTemplate = GsonUtil.toAny(result, ResponseTemplate::class.java)
        }
        return responseTemplate?.data
    }
}